import { defineStore } from 'pinia'
import { login as loginApi, getAccount } from '@/apis/auth'
import { removeToken, setToken } from '@/utils/token'
import router, { toLogin, toHome, resetRouter } from '@/router'
import { addAysncRoutes } from '@/router/routes';

export const useAccountStore = defineStore('account', {
    state() {
        return {
            info: {},
        }
    },
    getters: {
        id() {
            return this.info?.id
        },
        name() {
            return this.info?.name
        },
        avatar() {
            return this.info?.avatar
        },
        roles() {
            return this.info?.roles || []
        },
        permissions() {
            return this.info?.permissions || []
        }
    },
    actions: {
        async getAccountInfo() {
            const data = await getAccount();

            if (data.code === 0) {
                const { id, name, avatar, roles, permissions } = data.content;
                this.info = { id, name, avatar, roles, permissions };

                addAysncRoutes(router);
                return Promise.resolve(data.content);
            }

            return Promise.reject(data.content);
        },

        async login(username, password) {
            const data = await loginApi({ name: username, password: password });

            if (data.code === 0) {
                $message.success('登录成功');
                setToken(data.content.token);
                this.info = data.content.account;

                addAysncRoutes(router);
                toHome();
            } else {
                $message.warning(resp.message);
            }
        },

        async logout() {
            removeToken();
            this.$reset();
            resetRouter();
            toLogin();
        },

        setAccountInfo(accountInfo = {}) {
            this.info = { ...this.info, ...accountInfo };
        },
    },
})